//
//  KAApplyResultVC.swift
//  kano
//
//  Created by Sophia on 2024/8/22.
//

import UIKit
import Kingfisher


enum KAApplyResult: Int {
    case success = 0
    case fail = 1
    case reviewing = 2
}

class KAApplyResultVC: KABaseVC, UIScrollViewDelegate {
    
    lazy var var_scrollView: UIScrollView = {
        let var_scrollView = UIScrollView(frame: CGRectMake(0, UIDevice.ka_fullNavHeight, view.width, UIDevice.ka_viewHeight))
        var_scrollView.backgroundColor = .colorFFF
        var_scrollView.isScrollEnabled = true
        var_scrollView.contentSize = CGSize(width: var_screenWidth, height: var_screenHeight)
        var_scrollView.bounces = true
        var_scrollView.delegate = self
        return var_scrollView
    }()
    
    lazy var var_resultImg: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    public var statuslLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.systemFont(ofSize: kscale(16), weight: .bold)
        label.textColor = .black
        label.textAlignment = .center
        label.text = ""
        return label
    }()
    public var symbolLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        label.font = UIFont.systemFont(ofSize: kscale(12), weight: .regular)
        label.textColor = UIColor.ka_hexColor(0x8F92A1)
        label.textAlignment = .center
        label.text = ""
        return label
    }()
    
    lazy var var_homeBtn: UIButton = {
        let var_homeBtn = UIButton()
        var_homeBtn.setTitle("Home", for: .normal)
        var_homeBtn.setTitleColor(.themeColor, for: .normal)
        var_homeBtn.titleLabel?.font = UIFont.systemFont(ofSize: kscale(17), weight: .bold)
        var_homeBtn.backgroundColor = .clear
        //        var_homeBtn.layer.cornerRadius = kscale(25)
        //        var_homeBtn.layer.masksToBounds = true
        var_homeBtn.addTarget(self, action: #selector(ka_var_homeBtnClick), for: .touchUpInside)
        return var_homeBtn
    }()
    @objc func ka_var_homeBtnClick() {
        navigationController?.popToRootViewController(animated: true)
    }
    
    lazy var var_cornerView: KAApplyResultBindcard = {
        let var_cornerView = KAApplyResultBindcard()
        var_cornerView.var_bindBtn.addTarget(self, action: #selector(ka_bindBtnClick), for: .touchUpInside)
        
        return var_cornerView
    }()
    
    @objc func ka_bindBtnClick() {
        let btnInfo = KABtnInfo(eleId: "lendTenor_adjust", pageId: "creditTerm_config", clickTime: Date.ka_currentData())
        KAReport.ka_reportWith(type: .btn, data: btnInfo.kj.JSONObject())
        
        KAFlutterManager.showFlutterVC(route: "/addBank", parameter: ["fromCredit" : true])
    }
    
    override func customNavBackAction() {
        navigationController?.popToRootViewController(animated: true)
    }
    
    var resultType: KAApplyResult = .reviewing
    var applyResult: KAApply = KAApply()
    
    var grayStatus: Int = 0
    
    var twoMinLater: Bool = false
    private var count: Int = 60
    private var task: String?
    
    private var isRequestActive = false
    
    init(reviewResult: KAApplyResult) {
        resultType = reviewResult
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    deinit {
        isRequestActive = false
        print("+++++")
    }
}

extension KAApplyResultVC {
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        isRequestActive = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ka_showCustomerNavBar(type: .normal)
        var_navBar.var_titleLabel.text = "Profile Verification"
        startTimer()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        var eleId = ""
        if resultType == .reviewing {
            eleId = "creditTerm_config"
        } else if resultType == .fail {
            eleId = "loanExit_continue"
        }
        let data = KAPageInfo(eleId: eleId, path: "\(KAInfoVC.self)")
        KAReport.ka_reportWith(type: .page, data: data.kj.JSONObject())
        
        isRequestActive = true
        checkUer()
        
    }
    
    func checkUer() -> Void {
        let paraDic = [
            "softwareUpdateVersions":KAUserManager.shared.user.softwareUpdateVersions, "relationType":"20",
        ]
        loginProvider.request(.checkUserType(paraDic)) { [self] result in
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAContent>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else { return }
                            grayStatus = content.waitingStateVariant
                            
                            ka_setUI()
                            if grayStatus == 1 {
                                requestApplyResult()
                            }
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    func requestApplyResult() -> Void {
        let paraDic = [
            "softwareUpdateVersions":KAUserManager.shared.user.softwareUpdateVersions,
        ]
        view.showLoading()
        loginProvider.request(.queryCreditResult(paraDic)) { [self] result in
            view.hideLoading()
            switch result {
            case .success(let response):
                if response.statusCode == 200 {
                    NetResponse<KAApply>.handleResponseData(response.data) { isSuccess, message, response in
                        if isSuccess {
                            guard let content = response?.voucherQuantity else { return }
                            applyResult = content
                            
                            if applyResult.creditCondition == 1 {
                                //reviewing
                                resultType = .reviewing
                                requestAgin()
                                return
                            }
                            if applyResult.creditCondition == -1 {
                                resultType = .fail
                                updateUI()
                                return
                            }
                            
                            if applyResult.creditCondition != 2 {
                                navigationController?.popToRootViewController(animated: true)
                                return
                            }
                            
//                            if applyResult.creditCondition == 2 {
//                                if (applyResult.creditTiming == "1" || applyResult.creditTiming == "3") && applyResult.installationRejectionFlag == "1" {
//                                    //被拒贷了
//                                    resultType = .fail
//                                    updateUI()
//                                } else if (applyResult.creditTiming == "8" || applyResult.creditTiming == "10") {
//                                    resultType = .reviewing
//                                    requestAgin()
//                                } else {
//                                    //可借额度>最小借款金额
//                                    if applyResult.currentammo == 0 && applyResult.bankingInstitutionIdentifier == 0 {
//                                        resultType = .reviewing
//                                        updateUI()
//                                        requestAgin()
//                                    } else if applyResult.currentammo >= applyResult.minimumThreshold  {
//                                        resultType = .success
//                                        updateUI()
//                                        applyAuto(borrowingLoanType: 1)
//                                    } else if applyResult.bankingInstitutionIdentifier >= applyResult.subLowestLimit {
//                                        resultType = .success
//                                        updateUI()
//                                        applyAuto(borrowingLoanType: 2)
//                                    }   else {
//                                        updateUI()
//                                        navigationController?.popToRootViewController(animated: true)
//                                    }
//                                    
//                                }
//                            }
                            
                            //大额
                            if applyResult.subLogicIndicator == 1 {
                                //被拒贷
                                if (applyResult.creditTiming == "1" || applyResult.creditTiming == "3") && applyResult.installationRejectionFlag == "1" {
                                    resultType = .fail
                                    updateUI()
                                } else {
                                    //可借额度>最小借款金额
                                    if applyResult.currentammo == 0 && applyResult.bankingInstitutionIdentifier == 0 {
                                        resultType = .reviewing
                                        updateUI()
                                        requestAgin()
                                    } else if applyResult.bankingInstitutionIdentifier >= applyResult.subLowestLimit {
                                        resultType = .success
                                        updateUI()
                                        applyAuto(borrowingLoanType: 2)
                                    }   else {
                                        updateUI()
                                        navigationController?.popToRootViewController(animated: true)
                                    }
                                }
                            } else {
                                //小额、蝌蚪贷
                                switch applyResult.creditTiming {
                                    //被拒绝
                                case "1": fallthrough
                                case "3":
                                    resultType = .fail
                                    updateUI()
                                    //审核中
                                case "8": fallthrough
                                case "10":
                                    resultType = .reviewing
                                    requestAgin()
                                default:
                                    if applyResult.currentammo == 0 && applyResult.bankingInstitutionIdentifier == 0 {
                                        resultType = .reviewing
                                        updateUI()
                                        requestAgin()
                                    } else if applyResult.currentammo >= applyResult.minimumThreshold  {
                                        resultType = .success
                                        updateUI()
                                        applyAuto(borrowingLoanType: 1)
                                    } else {
                                        updateUI()
                                        navigationController?.popToRootViewController(animated: true)
                                    }
                                }
                            }
                        } else {
                            requestAgin()
                        }
                    }
                }else {
                    self.view.makeToast(badNetWorking)
                }
            case .failure(let error):
                print(error.localizedDescription)
            }
        }
    }
    
    func requestAgin() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 10) { [self] in
            if isRequestActive {
                self.requestApplyResult()
            }
        }
    }
    
    func applyAuto(borrowingLoanType: Int) {
        NetService.applyAuto(borrowingLoanType: borrowingLoanType) { isSuccess, message, response in
            
        }
    }
    
    func ka_setUI() {
        view.addSubview(var_scrollView)
        var_scrollView.backgroundColor = .colorf2f2f5
        var_scrollView.addSubview(var_resultImg)
        var_scrollView.addSubview(statuslLabel)
        var_scrollView.addSubview(symbolLabel)
        var_scrollView.addSubview(var_cornerView)
        var_scrollView.addSubview(var_homeBtn)
        
        updateUI()
    }
    
    func updateUI() {
        if resultType != .reviewing {
            var_resultImg.image = (resultType == .success) ? UIImage(named: "apply_success") : UIImage(named: "apply_fail")
        } else {
            let gifURL = Bundle.main.url(forResource: "apply_reviewing", withExtension: "gif")
            var_resultImg.kf.setImage(
                with: gifURL,
                placeholder: nil,
                completionHandler: { result in
                    switch result {
                    case .success(let value):
                        print("GIF success from：\(value.cacheType)")
                    case .failure(let error):
                        print("GIF fail from：\(error)")
                    }
                }
            )
        }
        if resultType == .fail {
            let tipStr = """
Thank you for using our loan service. We regret to inform you that your credit application was not approved due to certain factors. The approval process takes into account various factors, such as credit history and financial status. If you have any questions, please feel free to contact our customer service team.

If you have concerns about your personal information, you can go to the account security page to deactivate your account, and we will delete all your data.

Thank you for your understanding. Wishing you all the best!
"""
            statuslLabel.text = ""
            symbolLabel.text = tipStr
        } else if resultType == .success {
            statuslLabel.text = ""
            symbolLabel.text = "Congratulations, your application has been approved."
        } else {
            statuslLabel.text = "Under review..."
            symbolLabel.text = twoMinLater ? "We are expediting the review of your information. Please be patient, and feedback is expected within 15 minutes." : "The review is expected to be completed in 40 seconds. Please wait."
        }
        
        
        
        var_resultImg.snp.makeConstraints { make in
            make.size.equalTo(CGSize(width: kscale(120), height: kscale(120)))
            make.top.equalTo(kscale(32))
            make.centerX.equalTo(view)
        }
        statuslLabel.snp.makeConstraints { make in
            make.left.equalTo(view).offset(kscale(20))
            make.right.equalTo(view).offset(kscale(-20))
            make.top.equalTo(var_resultImg.snp.bottom).offset(kscale(18))
        }
        symbolLabel.snp.makeConstraints { make in
            make.left.equalTo(view).offset(kscale(20))
            make.right.equalTo(view).offset(kscale(-20))
            make.top.equalTo(statuslLabel.snp.bottom).offset(kscale(18))
        }
        
        var_cornerView.snp.remakeConstraints { make in
            make.left.equalTo(view).offset(kscale(20))
            make.right.equalTo(view).offset(kscale(-20))
            make.top.equalTo(symbolLabel.snp.bottom).offset(kscale(24))
            if grayStatus == 0 || resultType == .fail {
                make.height.equalTo(0)
            } else {
                make.height.equalTo(kscale(192))
            }
        }
        var_homeBtn.snp.makeConstraints { make in
            make.left.equalTo(view).offset(kscale(20))
            make.right.equalTo(view).offset(kscale(-20))
            make.top.equalTo(var_cornerView.snp.bottom).offset(kscale(40))
            make.height.equalTo(kscale(50))
        }
    }
    
    private func startTimer() {
        count = 10
        task = KATimer.execTask(self, selector: #selector(countdown), start: 0.0, interval: 1.0, repeats: true, async: false)
    }
    
    @objc private func countdown() {
        if count > 0 {
            count -= 1
        } else {
            KATimer.cancelTask(task!)
            twoMinLater = true
            updateUI()
        }
    }
}
